
class TaskQueue {

    constructor() {
        this.queue = [];
        this.running = false;
    }


    push(task, delay = 0) {
        this.queue.push({ task, delay });
        if (!this.running) {
            this.run();
        }
    }

    async run() {
        if (this.running || this.queue.length === 0) {
            return;
        }

        this.running = true;
        const { task, delay } = this.queue.shift();

        await new Promise(resolve => setTimeout(resolve, delay));

        try {
            const result = await task();
            if (result === true) {
                setImmediate(() => this.run()); // 使用setImmediate将下一个任务添加到事件循环中，以便在后台执行
            }
        } catch (error) {
            console.error('An error occurred while executing the task:', error);
        }

        this.running = false;
    }
}



module.exports = TaskQueue;
